<?php
/**
 * Created by PhpStorm.
 * User: zoupeng
 * Date: 2019-02-17
 * Time: 17:32
 */

namespace app\index\model;


use think\exception\ErrorException;
use think\Model;
use think\Log;

class Goods extends Model
{
    /**
     * @Notes:   按条件、分页搜索商品（自动分页搜索，不需要填页数）（需要）
     * @User:    this邹
     * @CreateDate:  2019/2/21 0021 17:18
     * @param string $title  标题
     * @param string $categoryId    分类ID
     * @param string $sort  排序
     * @param string $couponRate     卷后价格
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function findGoodsList($title = '', $categoryId = '', $sort = '',$couponRate='',$goodsIdArr=[],$volume='')
    {
        // 排序搜索条件
        $order = '';
        if (!$sort) {
            $sort = preg_replace('# #', '', config('web.WEB_SORT'));
        }
        switch ($sort) {
            case 'new'  :$order = 'addTime desc';break;// 产品添加时间
            case 'price':$order = 'couponPrice desc';break;// 产品现价
            case 'hot'  :$order = 'volume desc';break;// 产品销量
            case 'quan' :$order = 'couponAmount desc';break;// 产品优惠卷面额
            case 'rate' :$order = 'couponRate asc';break;// 产品卷后价
        }

        // 搜索条件
        $searchWhere = array();
        // 是否显示 1为显示 0为不显示
        $searchWhere['show'] = 1;
        // 按产品分类ID搜索
        if ($categoryId) {
            $searchWhere['cid'] = $categoryId;
        }
        // 按产品ID搜索
        if($goodsIdArr){
            $searchWhere['id'] = ['in',$goodsIdArr];
        }
        // 按劵后价搜索
        if($couponRate){
            switch ($couponRate){
                case 10:$searchWhere['couponRate'] = ['<',$couponRate];break;
                case 20:$searchWhere['couponRate'] = ['<=',$couponRate];break;
            }
        }
        // 按销量
        if($volume){
            $searchWhere['volume'] = ['>',$volume];
        }

//        dump($this->field('id,cid,uid,title,pic,show,numIid,couponPrice,couponRate,commissionUser,nick,couponAmount,volume,userType,clickUrl')
//            ->where($searchWhere)
//            ->where('title', 'like', '%' . $title . '%')
//            ->order($order)->fetchSql(true)->limit(20)->select());
        try {
//            $GoodsList = $this->alias('G')
//                ->join('category C', 'C.id=G.cid')
//                ->field('G.id,G.uid,G.title,G.pic,G.show,G.numIid,G.couponPrice,G.couponRate,G.commissionUser,G.nick,G.couponAmount,G.volume,G.userType,G.clickUrl,C.id as cid,C.name')
//                ->where($searchWhere)
//                ->where('title','like','%'.$title.'%')
//                ->order($order)
//                ->paginate(40,false);

            // 产品数量 todo 后期优化  不要这个查询总数
            $goodsCount = $this->where($searchWhere)
                ->where('title', 'like', '%' . $title . '%')
                ->order($order)
                ->count();

            // 产品数据
            $goodsList = $this->field('id,cid,uid,title,pic,numIid,couponPrice,couponRate,commissionUser,nick,couponAmount,userType,volume,clickUrl')
                ->where($searchWhere)
                ->where('title', 'like', '%' . $title . '%')
                ->order($order)
                ->paginate(40, false);

            return array('goodsCount'=>$goodsCount,'goodsList'=>$goodsList);
        } catch (ErrorException $e) {
            Log::write('查找产品异常，错误信息：' . $e->getMessage(), 'error');
        }
    }

    /**
     * 检测产品是否存在 id
     * @param $goodsId  产品主键ID
     * @return bool
     */
    public function isTrueGoodsById($goodsId){
        try{
            $isId = $this->where('id',$goodsId)->value('id');
            if($isId){
                return true;
            }else{
                return false;
            }
        }catch(ErrorException $e){
            Log::write('检测产品是否存在异常产品ID:'.$goodsId.'、错误信息：'.$e->getMessage(), 'error');
        }
    }

    /**
     * 检测产品是否存在 numIid
     * @param $numIid  产品numIid
     * @return bool
     */
    public function isTrueGoodsByNumIid($numIid){
        try{
            $isId = $this->where('numIid',$numIid)->value('id');
            if($isId){
                return true;
            }else{
                return false;
            }
        }catch(ErrorException $e){
            Log::write('检测产品是否存在异常产品numIid:'.$numIid.'、错误信息：'.$e->getMessage(), 'error');
        }
    }

    /**
     * 产品浏览量+1
     * @param $goodsId  产品ID
     * @return bool
     * @throws \think\Exception
     */
    public function increaseView($goodsId){
        try{
            $isTrue = $this->where('id',$goodsId)->setInc('view', 1);
            if($isTrue){
                return true;
            }else{
                return false;
            }
        }catch(ErrorException $e){
            Log::write('产品浏览量+1异常产品ID:'.$goodsId.'、错误信息：'.$e->getMessage(),'error');
        }
    }

    /**
     * 根据产品ID获取产品详细信息
     * @param $goodsId  产品主键ID
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsById($goodsId){
        try{
            $goodsItem = $this->field('id,cid,numIid,title,pic,price,couponPrice,couponRate,commissionUser,nick,taoToken,couponAmount,volume,clickUrl,description,content,keywords')->find($goodsId);
            $goodsItem['content'] = htmlspecialchars_decode($goodsItem['content']);// 把预定义的字符转换为 HTML 实体：
            return $goodsItem;
        }catch(ErrorException $e){
            Log::write('查找产品异常产品ID:'.$goodsId.'、错误信息：'.$e->getMessage(),'error');
        }
    }

    /**
     * 根据产品NumIid获取指定字段值信息
     * @param $goodsNumIid 产品NumIid
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsByNumIid($goodsNumIid){
        try{
            $goodsItem = $this->field('id,cid,numIid,title,pic,price,couponPrice,couponRate,commissionUser,nick,taoToken,couponAmount,volume,clickUrl,description,content,keywords')->where('numIid',$goodsNumIid)->find();
            $goodsItem['content'] = htmlspecialchars_decode($goodsItem['content']);// 把预定义的字符转换为 HTML 实体：
            return $goodsItem;
        }catch(ErrorException $e){
            Log::write('查找产品异常产品NumIid:'.$goodsNumIid.'、错误信息：'.$e->getMessage(),'error');
        }
    }


}